


from django.apps import AppConfig
from django.core import checks

class LoggerConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'logger'
    verbose_name = "日志系统"
    
    # 自定义配置
    LOG_LEVEL = 'INFO'
    ENABLE_CONSOLE_LOGGING = True
    
    def ready(self):
        """
        日志系统初始化
        """
        # 1. 导入接收器以注册信号
        import logger.receivers
        
        # 2. 配置日志系统
        self._configure_logging()
        
        print(f"📝 {self.verbose_name} 已初始化完成")
    
    # 使用装饰器注册检查函数
    @staticmethod
    @checks.register('security')
    def check_logging_config(**kwargs):
        """
        检查日志配置
        """
        from django.conf import settings
        from django.core.checks import Warning
        
        warnings = []
        
        # 检查是否配置了日志
        if not hasattr(settings, 'LOGGING') or not settings.LOGGING:
            warnings.append(
                Warning(
                    '未配置日志记录',
                    hint='在 settings.py 中添加 LOGGING 配置',
                    id='logger.W001',
                )
            )
        
        return warnings
    
    def _configure_logging(self):
        """动态配置日志系统"""
        import logging.config
        from django.conf import settings
        
        # 如果用户没有配置日志，则使用默认配置
        if not hasattr(settings, 'LOGGING') or not settings.LOGGING:
            # 使用 try-except 避免在迁移过程中出错
            try:
                logging_config = {
                    'version': 1,
                    'disable_existing_loggers': False,
                    'handlers': {
                        'console' if self.ENABLE_CONSOLE_LOGGING else 'null': {
                            'class': 'logging.StreamHandler',
                            'level': self.LOG_LEVEL,
                        },
                    },
                    'root': {
                        'handlers': ['console'] if self.ENABLE_CONSOLE_LOGGING else [],
                        'level': self.LOG_LEVEL,
                    },
                }
                logging.config.dictConfig(logging_config)
                print(f"📊 已使用默认日志配置: 级别={self.LOG_LEVEL}, 控制台输出={'启用' if self.ENABLE_CONSOLE_LOGGING else '禁用'}")
            except Exception as e:
                print(f"⚠️ 警告: 配置日志时出错: {e}")